package com.benmei.api;

import android.content.Context;

import com.benmei.bean.HomePage;
import com.benmei.config.Url;
import com.benmei.waijiaojun.MyApplication;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;


/**
 * 描述：请求管理类
 * 作者：husunxing
 * 创建日期：2017/11/29
 * 邮箱：husunxing@outlook.com
 */

public class ApiManager {
    private static final String TAG = "ApiManager";
    private Retrofit mRetrofit;
    private ApiService apiService;
    private static Context mContext;
    private static ApiManager apiManager;

    //初始化Retrofit
    private ApiManager(Context context) {
        mContext = context;

        mRetrofit = new Retrofit.Builder()
                .baseUrl(Url.BASEURL)                                       //设置访问环境
                .client(OkHttpClientManager.getClinet(mContext))            //设置OKhttpclient
                .addConverterFactory(GsonConverterFactory.create())          //设置Gson解析器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())   //设置Rxjava适配器
                .build();

        if (apiService == null) {
            apiService = mRetrofit.create(ApiService.class);
        }
    }

    /**
     * 获取单例ApiManager对象
     *
     * @return
     */
    public static ApiManager getInstance() {
        if (apiManager == null) {
            synchronized (ApiManager.class) {
                if (apiManager == null)
                    apiManager = new ApiManager(MyApplication.getContext());
            }
        }
        return apiManager;
    }

    /**
     * 清除ApiManager对象
     */
    public static void cencleApimanager() {
        if (apiManager != null) {
            apiManager = null;
        }
    }

    public Observable<HomePage> getHomeData() {
        return apiService.getHomeData().compose(RxResultHelper.<HomePage>result());
    }



}
